package com.quiz.bis.util.text;

import com.quiz.bis.domain.model.ProcessedText;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import com.quiz.file.domain.model.FileInfo;
import com.quiz.file.mapper.FileMapper;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 文本预处理工具类
 */
@Component
public class TextPreprocessor {
//    private static final Pattern FORMULA_PATTERN =
//            Pattern.compile("<span data-w-e-type=\"formula\"[^>]*data-value=\"([^\"]*)\"");
    private static final Pattern FORMULA_PATTERN =
            Pattern.compile("<span data-w-e-type=\"formula\"[^>]*data-value=\"([^\"]*)\"");

    private static final Pattern IMAGE_PATTERN =
            Pattern.compile("<img[^>]*src=\"([^\"]*)\"");
    private static final Pattern TABLE_PATTERN =
            Pattern.compile("<table[^>]*>.*?</table>", Pattern.DOTALL);
    private static final Pattern IMAGE_ID_PATTERN =
            Pattern.compile("/(\\d+)(\\?|$)");

    private final FileMapper fileMapper;

    public TextPreprocessor(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
    }

    /**
     * 预处理HTML文本
     * @param html 原始HTML
     * @return 预处理后的文本信息
     */
    public ProcessedText preprocess(String html) {
        if (html == null || html.isEmpty()) {
            return new ProcessedText("", new ArrayList<>(),
                    new ArrayList<>(), new ArrayList<>(),
                    new ArrayList<>());
        }

        // 提取公式
        List<String> formulas = extractFormulas(html);

        // 提取图片ID
        List<Long> imageIds = extractImageIds(html);

        // 提取表格
        List<String> tables = extractTables(html);

        // 清理HTML获取纯文本
        String cleanText = cleanHtml(html);

        // 分词处理
        List<String> words = segmentText(cleanText);

        return new ProcessedText(cleanText, words, formulas, imageIds, tables);
    }

    /**
     * 清理HTML标签，保留纯文本
     */
    public String cleanHtml(String html) {
        // 使用Jsoup清理HTML，保留换行
        String text = Jsoup.clean(html, Safelist.none());
        // 替换多个空白字符为单个空格
        return text.replaceAll("\\s+", "").trim();
    }

    /**
     * 对文本进行分词
     */
    private List<String> segmentText(String text) {
        if (text == null || text.isEmpty()) {
            return new ArrayList<>();
        }
        return HanLP.segment(text).stream()
                .map(e -> e.word)
                .filter(word -> word != null && !word.trim().isEmpty())
                .collect(Collectors.toList());
    }

    /**
     * 提取公式
     */
    private List<String> extractFormulas(String html) {
        html = html.replace("\\","");
        List<String> formulas = new ArrayList<>();
        Matcher matcher = FORMULA_PATTERN.matcher(html);
        while (matcher.find()) {
            formulas.add(matcher.group(1));
        }
        return formulas;
    }

    /**
     * 提取图片ID
     */
    private List<Long> extractImageIds(String html) {
        List<Long> imageIds = new ArrayList<>();
        Matcher matcher = IMAGE_PATTERN.matcher(html);
        while (matcher.find()) {
            String src = matcher.group(1);
            Long imageId = extractIdFromUrl(src);
            if (imageId != null) {
                imageIds.add(imageId);
            }
        }
        return imageIds;
    }

    /**
     * 从URL中提取ID
     */
    private Long extractIdFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        Matcher matcher = IMAGE_ID_PATTERN.matcher(url);
        if (matcher.find()) {
            try {
                return Long.parseLong(matcher.group(1));
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取图片文件路径
     */
    public String getImagePath(Long fileId) {
        if (fileId == null) {
            return null;
        }
        FileInfo fileInfo = fileMapper.selectById(fileId);
        return fileInfo != null ? fileInfo.getFilePath() : null;
    }

    /**
     * 提取表格
     */
    private List<String> extractTables(String html) {
        List<String> tables = new ArrayList<>();
        Matcher matcher = TABLE_PATTERN.matcher(html);
        while (matcher.find()) {
            tables.add(matcher.group());
        }
        return tables;
    }
}